/*
 * EbayManager.java
 *
 * Created on August 4, 2006, 10:43 PM
 */

package com.thornapple.ebay.manager;

import ca.odell.glazedlists.BasicEventList;
import ca.odell.glazedlists.EventList;
import ca.odell.glazedlists.FilterList;
import ca.odell.glazedlists.GlazedLists;
import ca.odell.glazedlists.SortedList;
import ca.odell.glazedlists.gui.AdvancedTableFormat;
import ca.odell.glazedlists.gui.WritableTableFormat;
import ca.odell.glazedlists.swing.EventTableModel;
import ca.odell.glazedlists.swing.TableComparatorChooser;
import com.ebay.sdk.util.eBayUtil;
import com.ebay.soap.eBLBaseComponents.ItemType;
import com.ebay.soap.eBLBaseComponents.ListingDetailsType;
import com.thornapple.ebay.manager.action.FindItemsAction;
import com.thornapple.ebay.manager.ui.MatcherFactory;
import com.thornapple.ebay.manager.ui.laf.ThButtonUI;
import com.thornapple.ebay.manager.ui.laf.ThPanelUI;
import java.awt.Color;
import java.util.Comparator;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import org.jdesktop.swingx.decorator.AlternateRowHighlighter;
import org.jdesktop.swingx.decorator.HighlighterPipeline;
import org.jdesktop.swingx.decorator.PatternFilter;

/**
 *
 * @author  Bill
 */
public class EbayManager extends javax.swing.JFrame {
    
    /*The main event list. Drives everything we do here in the manager.*/
    private EventList itemEventList = new BasicEventList();
    
    /*Create a sorted list for the table*/
    private SortedList sortedItems = new SortedList(itemEventList, new AuctionItemComparator());
    
    /*Create a list filtered by the ItemFilterPanel*/
    private FilterList filteredList;
    
    /*Create the criteria bean.*/
    private ItemSearchCriteria criteria = new ItemSearchCriteria();
    
    //table setup
    final String[] colNames = new String[] {
        ""," Title", "SubTitle", "Price", "Shipping", "BidCount", "EndTime"};
    
    
    /** Creates new form EbayManager */
    public EbayManager() {
        initComponents();
        this.getContentPane().setBackground(Color.WHITE);
        final PatternFilter patternFilter = new PatternFilter();
        patternFilter.setColumnIndex(2);
        
//        filterTextField.addKeyListener(new KeyListener() {
//            public void keyTyped(KeyEvent e) {
//                try {
//                    patternFilter.setPattern(Pattern.compile(filterTextField.getText()));
//                } catch (Exception e1) {
//                }
//            }
//
//            public void keyPressed(KeyEvent e) {
//            }
//
//            public void keyReleased(KeyEvent e) {
//            }
//        });
//        tblResults.setFilters(new FilterPipeline(new Filter[]{patternFilter}));
        
        //table setup
        
        MatcherFactory matcherFactory = MatcherFactory.getInstance();
        filteredList = new FilterList(sortedItems,matcherFactory.createMatcher(itemEventList,itemFilterPanel1));
        
        EventTableModel itemTableModel = new EventTableModel(filteredList, new ItemTableFormat());
        tblResults.setModel(itemTableModel);
        TableComparatorChooser tableSorter = new TableComparatorChooser(tblResults, sortedItems, true);
        
        
        jButton1.setUI(new ThButtonUI());
        //itemSearchPanel.setUI(new ThPanelUI());
        //itemFilterPanel1.setUI(new ThPanelUI());
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        jButton1 = new javax.swing.JButton();
        itemSearchPanel = new com.thornapple.ebay.manager.ui.ItemSearchPanel();
        itemSearchPanel.setCriteria(criteria);
        jLabel1 = new javax.swing.JLabel();
        jComboBox1 = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();
        jXHyperlink1 = new org.jdesktop.swingx.JXHyperlink();
        jXHyperlink2 = new org.jdesktop.swingx.JXHyperlink();
        itemFilterPanel1 = new com.thornapple.ebay.manager.ui.ItemFilterPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblResults = new org.jdesktop.swingx.JXTable();
        HighlighterPipeline highlighter = new HighlighterPipeline();
        highlighter.addHighlighter(new AlternateRowHighlighter());
        tblResults.setHighlighters(highlighter);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setBackground(java.awt.Color.white);
        jButton1.setText("Find It!");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel1.setText("Actions:");

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Apply label", "Add to My Ebay" }));

        jLabel2.setText("Select:");

        jXHyperlink1.setText("All");

        jXHyperlink2.setText("None");

        tblResults.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        tblResults.setSortable(false);
        jScrollPane1.setViewportView(tblResults);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(itemFilterPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 373, Short.MAX_VALUE)
                    .add(itemSearchPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 373, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jButton1))
                .add(6, 6, 6)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .add(jLabel2)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jXHyperlink1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jXHyperlink2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 138, Short.MAX_VALUE))
                    .add(layout.createSequentialGroup()
                        .add(jLabel1)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jComboBox1, 0, 174, Short.MAX_VALUE))
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 217, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(jLabel1)
                            .add(jComboBox1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(jXHyperlink1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(jXHyperlink2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(jLabel2))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 423, Short.MAX_VALUE))
                    .add(layout.createSequentialGroup()
                        .add(itemSearchPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jButton1)
                        .add(21, 21, 21)
                        .add(itemFilterPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 262, Short.MAX_VALUE)))
                .addContainerGap())
        );
        pack();
    }// </editor-fold>//GEN-END:initComponents
    
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        itemSearchPanel.commit();
        new FindItemsAction(itemEventList,criteria).actionPerformed(null);
    }//GEN-LAST:event_jButton1ActionPerformed
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                } catch (InstantiationException ex) {
                    ex.printStackTrace();
                } catch (IllegalAccessException ex) {
                    ex.printStackTrace();
                } catch (ClassNotFoundException ex) {
                    ex.printStackTrace();
                }
                new EbayManager().setVisible(true);
            }
        });
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private com.thornapple.ebay.manager.ui.ItemFilterPanel itemFilterPanel1;
    private com.thornapple.ebay.manager.ui.ItemSearchPanel itemSearchPanel;
    private javax.swing.JButton jButton1;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private org.jdesktop.swingx.JXHyperlink jXHyperlink1;
    private org.jdesktop.swingx.JXHyperlink jXHyperlink2;
    private org.jdesktop.swingx.JXTable tblResults;
    // End of variables declaration//GEN-END:variables
    
    
    class AuctionItemComparator implements Comparator {
        public int compare(Object a, Object b) {
            AuctionItem itemA = (AuctionItem)a;
            AuctionItem itemB = (AuctionItem)b;
            
            //initially sort by cost, lower is more important
            double itemAValue = itemA.getCurrentPrice();
            double itemBValue = itemB.getCurrentPrice();
            
            return new Double(itemAValue - itemBValue).intValue();
        }
    }
    
    class AuctionItemTextComparator implements Comparator {
        public int compare(Object a, Object b) {
            AuctionItem itemA = (AuctionItem)a;
            AuctionItem itemB = (AuctionItem)b;
            
            //initially sort by cost, lower is more important
            double itemAValue = itemA.getCurrentPrice();
            double itemBValue = itemB.getCurrentPrice();
            
            return new Double(itemAValue - itemBValue).intValue();
        }
    }
    
    class AuctionItemDateComparator implements Comparator {
        public int compare(Object a, Object b) {
            AuctionItem itemA = (AuctionItem)a;
            AuctionItem itemB = (AuctionItem)b;
            
            //initially sort by cost, lower is more important
            double itemAValue = itemA.getCurrentPrice();
            double itemBValue = itemB.getCurrentPrice();
            
            return new Double(itemAValue - itemBValue).intValue();
        }
    }
    
    class AuctionItemCostComparator implements Comparator {
        public int compare(Object a, Object b) {
            
            double itemAValue = 0;
            double itemBValue = 0;
            
            if (a == null)
                itemAValue = 0;
            else if (a instanceof String && ((String)a).length() > 0)
                itemAValue = new Double((String)a);
            else if (a instanceof Double)
                itemAValue = (Double)a;
            else
                itemAValue = 0;
            
            if (b == null)
                itemBValue = 0;
            else if (b instanceof String && ((String)b).length() > 0)
                itemAValue = new Double((String)b);
            else if (b instanceof Double)
                itemBValue = (Double)b;
            else
                itemBValue = 0;
            
            Double result = itemBValue - itemAValue;
            
            if (result > 0)
                return -1;
            else if (result < 0)
                return 1;
            else
                return 0;
            
        }
    }
    
    class ItemTableFormat implements AdvancedTableFormat, WritableTableFormat  {
        
        public int getColumnCount() {
            return colNames.length;
        }
        
        public String getColumnName(int column) {
            return colNames[column];
        }
        
        public Object getColumnValue(Object baseObject, int column) {
            AuctionItem auctionItem = (AuctionItem)baseObject;
            ItemType item = auctionItem.getItem();
            ListingDetailsType dtl = item.getListingDetails();
            
            if (column == 0) return auctionItem.isStarred();
            else if (column == 1) return item.getTitle();
            else if (column == 2) return item.getSubTitle() == null ? "" : item.getSubTitle();
            else if (column == 3) return auctionItem.getCurrentPrice();
            else if (column == 4 && auctionItem.isShippingCostAvailable()) return auctionItem.getShippingCost();
            else if (column == 5) return item.getSellingStatus().getBidCount();
            else if (column == 6) return eBayUtil.toAPITimeString(dtl.getEndTime().getTime());
            else
                return "";
        }
        
        public Class getColumnClass(int i) {
            if (i == 0)
                return Boolean.class;
            else
                return String.class;
        }
        
        public Comparator getColumnComparator(int column) {
            if (column == 0) return GlazedLists.booleanComparator();
            else if (column == 1) return GlazedLists.caseInsensitiveComparator();
            else if (column == 2) return GlazedLists.caseInsensitiveComparator();
            else if (column == 3) return new AuctionItemCostComparator();
            else if (column == 4) return new AuctionItemCostComparator();
            else if (column == 5) return GlazedLists.comparableComparator();
            else if (column == 6) return GlazedLists.comparableComparator();
            else return GlazedLists.caseInsensitiveComparator();
        }
        
        public boolean isEditable(Object o, int i) {
            if (i == 0) return true;
            else return false;
        }
        
        public Object setColumnValue(Object baseObject, Object editedObject, int i ) {
            System.out.println((Boolean)editedObject);
            if ( i == 0 )
                ((AuctionItem)baseObject).setStarred( (Boolean)editedObject );
            return baseObject;
        }
    }
    
}
